package com.ocom.srvpaccess.controller;

import com.ocom.common.constant.SrvpAccessDeviceUrl;
import com.ocom.common.entity.access.EntityMjDeviceInfo;
import com.ocom.common.entity.access.EntityMjGroupPer;
import com.ocom.common.entity.access.EntityMjWhiteInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.MachEnum;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.utils.AES;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.MD5;
import com.ocom.common.utils.RespUtilMach;
import com.ocom.common.vo.WhiteListVo;
import com.ocom.srvpaccess.service.GroupPerService;
import com.ocom.srvpaccess.service.MjDeviceInfoService;
import com.ocom.srvpaccess.service.PersonnelInfoService;
import com.ocom.srvpaccess.service.WhiteInfoService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName: ocom30
 * @Package: com.ocom.srvpaccessdevice.controller
 * @ClassName: WhiteListController
 * @Author: OCOM
 * @Description: 获取人员白名单
 * @Date: 2021/12/6 9:45
 * @Version: 3.0
 */

@Slf4j
@RestController
public class WhiteListController {
    Logger logger= LoggerFactory.getLogger(WhiteListController.class);
    @Autowired
    private MjDeviceInfoService mjDeviceInfoService;

    @Autowired
    private WhiteInfoService whiteInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private GroupPerService groupPerService;

    @GetMapping(value = SrvpAccessDeviceUrl.URLP_ACCESSDEVICE_getWhiteList)
    public RespMachMessage getWhiteList(Long companyId, String machNo, Integer listLimit){

        //获取白名单参数

        //判断设备id
        if (machNo == null || companyId == null){
            //    return RespUtilMach.error(MachEnum.PARAMS_ERROR);
            //    PARAMS_ERROR("0004","参数不匹配或参数错误"),
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }

        //返回参数
        Map<String,Object> map=new HashMap<>();

        //1从设备信息表mj_device_info找到com_id ，device_no匹配的记录得到 areaId。
        EntityMjDeviceInfo entityMjDeviceInfo = mjDeviceInfoService.selectAreaNo(companyId, machNo);
        if(entityMjDeviceInfo==null ||  entityMjDeviceInfo.getAreaId()==null){
            //找不到绑定区域
            //MACH_NOT_MSG("0401","设备无数据或当前位置无记录"),
            return RespUtilMach.error(MachEnum.MACH_NOT_MSG);

        }

        Long areaId = entityMjDeviceInfo.getAreaId();

        //获取list_add值
        Long listAdd = entityMjDeviceInfo.getListAdd();


        //2. 判断listadd == -1
        if (listAdd == -1){
            //2、如果list_add=-1：（全量下传）
            Long listAddTab = 0L;
            Long listDeleteTab = -1L;
            //list_delete=mj_white_info表中area_id=areaNo、state=1的最大id值
            EntityMjWhiteInfo whiteInfo = whiteInfoService.selectMaxId(companyId, areaId);
            if (whiteInfo != null){
                mjDeviceInfoService.updateDeviceInfo(companyId,machNo,listAddTab, listDeleteTab,whiteInfo.getId());
            }
            if (whiteInfo == null){
                mjDeviceInfoService.updateDeviceInfo(companyId,machNo,listAddTab, listDeleteTab,0L);
            }

            //修改mj_device_info表

            map.put("model",0);
            map.put("flag",2);
            return RespUtilMach.success(map);
        }

        //3. 检查是否有新的删除操作
        Long listDelete = entityMjDeviceInfo.getListDelete();
        List<EntityMjWhiteInfo> selectDeleteWhiteInfo = whiteInfoService.selectDeleteWhiteInfo(companyId,areaId, listDelete, listLimit);

        //检查是否有新的删除操作,如果有
        List<Long> pId = selectDeleteWhiteInfo.stream().map(EntityMjWhiteInfo::getPId).collect(Collectors.toList());
        ArrayList<Object> list1 = new ArrayList<>();
        if (!selectDeleteWhiteInfo.isEmpty()){
            Long listAddTab = -1L;
            for (EntityMjWhiteInfo entityMjWhiteInfo: selectDeleteWhiteInfo) {
                WhiteListVo whiteListVo = new WhiteListVo();
                whiteListVo.setP_ID(entityMjWhiteInfo.getPId());
                list1.add(whiteListVo);
            }

            try {
                Long maxId = selectDeleteWhiteInfo.stream().mapToLong(EntityMjWhiteInfo::getId).max().getAsLong();
                mjDeviceInfoService.updateListDel(companyId,machNo,listAddTab,maxId);
            }catch (Exception exception){
                exception.printStackTrace();
            }

            map.put("model",1);
            map.put("flag",1);
            map.put("list",list1);
            return RespUtilMach.success(map);

        }

        // 4. 检查是否有新的增加操作
        List<EntityMjWhiteInfo> selectAddWhiteInfo = whiteInfoService.selectAddWhiteInfo(companyId,areaId, listAdd, listLimit);
        if (selectAddWhiteInfo.size()!=0){
            List<Long> pIds = selectAddWhiteInfo.stream().map(EntityMjWhiteInfo::getPId).collect(Collectors.toList());
            // a)从人员信息表personnel_info找到com_id ，p_id匹配的记录，获取P_Name、pictureurl
            List<EntityPersonnelInfo> entityPersonnelInfos = personnelInfoService.selectPerInfo(companyId, pIds);
            log.info("白名单获取结果5, 【{}】",entityPersonnelInfos);
            List<EntityMjGroupPer> entityMjGroupPer = groupPerService.selectGroupPer(companyId, pIds, areaId);

            //检查是否有新的增加操作,如果有
            List<Object> list = new ArrayList<>();
            if (!selectAddWhiteInfo.isEmpty()) {
                Long listDeleteTab = -1L;
                //list转map
                Map<Long, Long> personGroupMap = new HashMap<>();
                if (entityMjGroupPer != null || entityMjGroupPer.size()>0) {
                    personGroupMap = entityMjGroupPer.stream().collect(Collectors.toMap(e -> e.getPId(),
                            e -> e.getGroupNo(),
                            (e1, e2) -> e1));
                }
                for (EntityPersonnelInfo personnelInfo : entityPersonnelInfos) {
                    if (entityMjGroupPer == null || entityMjGroupPer.size()==0 || !personGroupMap.containsKey(personnelInfo.getPId())) {
                        continue;
                    }
                    WhiteListVo whiteListVo = new WhiteListVo();

                    //人员ID
                    whiteListVo.setP_ID(personnelInfo.getPId());
                    if(personnelInfo.getCardState()==1 && !CommonUtil.isNull(personnelInfo.getCardNo())){
                        whiteListVo.setCard_No(personnelInfo.getCardNo());
                    }
                    //人员姓名
                    whiteListVo.setP_Name(personnelInfo.getPName());
                    //人脸图片url
                    whiteListVo.setPictureurl(personnelInfo.getPPhotoUrl());
                    if(CommonUtil.isNull(personnelInfo.getPPhotoUrl())){
                        whiteListVo.setPictureurl(personnelInfo.getPPhotoUrl2());
                    }
                    whiteListVo.setPergroupnum(personGroupMap.get(personnelInfo.getPId()));
                    String key = MD5.MD5Encode(companyId.toString(), "utf8");
                    whiteListVo.setIdentitynum(AES.decrypt(personnelInfo.getEncryIdentity(), key));
//                    whiteListVo.setCard_No("");
                    whiteListVo.setCardType(1);
                    list.add(whiteListVo);
                    map.put("model", 1);
                    map.put("flag", 2);
                    map.put("list", list);
                }
                try {
                    Long maxId = selectAddWhiteInfo.stream().mapToLong(EntityMjWhiteInfo::getId).max().getAsLong();
                    mjDeviceInfoService.updateListAdd(companyId, machNo, listDeleteTab, maxId);
                }catch (Exception exception){
                    exception.printStackTrace();
                }

            }
            logger.info("map{{}}",map);
            return RespUtilMach.success(map);
        }
        mjDeviceInfoService.updatePerNo(companyId,machNo);
        map.put("model",1);
        map.put("flag",2);
        logger.info("map{{}}",map);
        return RespUtilMach.success(map);
    }


    @PostMapping(value = SrvpAccessDeviceUrl.URLP_ACCESSDEVICE_changeWhiteListState)
    public RespMachMessage changeWhiteListState(Long companyId, String machNo){
        //判断设备id
        if (machNo == null || companyId <= 0){
            return RespUtilMach.error(MachEnum.PARAMS_ERROR);
        }
        //1、从门禁设备表mj_device_info找到device_no = machNo的记录。
        EntityMjDeviceInfo deviceInfo = mjDeviceInfoService.selectAreaNo(companyId, machNo);

        if(deviceInfo ==null ||  deviceInfo.getAreaId() ==null || deviceInfo.getAreaId() < 0 ){
            //找不到绑定区域
            return RespUtilMach.error(MachEnum.MACH_NOT_MSG);
        }
        Map<String, Object> map = new HashMap<>();
        //门禁区域areaNo = mj_device_info . area_id
        Long areaId = deviceInfo.getAreaId();

        //    从门禁设备标志表Card_White_recode找到MachID匹配的记录。
//        QueryWrapper<EntityCardWhiteRecode> cardWhiteRecodeQueryWrapper=new QueryWrapper<>();
//        cardWhiteRecodeQueryWrapper.eq("MachID",machInfo.getId());
//        cardWhiteRecodeQueryWrapper.select("top 1*");
//        EntityCardWhiteRecode cardWhiteRecode=cardWhiteRecodeService.getOne(cardWhiteRecodeQueryWrapper);
//
//        if(cardWhiteRecode==null){
//            return RespUtilMach.error(MachEnum.MACH_NOT_MSG);
//        }
//        //更新  cardWhiteRecode
//        UpdateWrapper<EntityCardWhiteRecode> cardWhiteRecodeUpdateWrapper=new UpdateWrapper<>();
//        Integer flag=255;

        //2、如果list_add_tab=-1 and list_delete_tab=-1：（已无新白名单）
        if(deviceInfo.getListAddTab()==-1 && deviceInfo.getListDeleteTab()==-1){
            //从门禁白名单mj_white_info再查找一次有没有新的白名单：
            //select id,p1 from mj_white_info
            //where area_no=’[areaNo]’ and ( id>[ mj_device_info .list_add] and State=0
            //or id>[ mj_device_info .list_delete] and State=1)
            List<EntityMjWhiteInfo> entityMjWhiteInfos = whiteInfoService.selectWhiteInfo(companyId, areaId, deviceInfo.getListAdd(), deviceInfo.getListDelete());

            /**
             *	如果没有：
             * 修改mj_device_info表：
             * update mj_device_info set list_state =0 where device_id=[deviceId] and list_State=2
             * 	  返回：flag=0
             * 	否则：
             * 修改mj_device_info表：	list_state=1
             * 	update mj_device_info set list_state =1 where device_id=[deviceId]
             * 返回：flag=255
             */
            if(entityMjWhiteInfos==null || entityMjWhiteInfos.isEmpty()){
                mjDeviceInfoService.updateListStateTwo(companyId,deviceInfo.getDeviceId());
                map.put("flag",0);
                return RespUtilMach.success(map);
            }else{
                mjDeviceInfoService.updateListStateOne(companyId,deviceInfo.getDeviceId());
                map.put("flag",255);
                return RespUtilMach.success(map);
            }
        }


        /**
         * 3、如果list_add_tab>=0 and list_delete_tab=-1：
         * 修改mj_device_info表：	list_add=list_add_tab
         * 	update mj_device_info set list_add = list_add_tab where device_id=[deviceId]
         * 	  返回：flag=255
         */
        if(deviceInfo.getListAddTab()>=0 && deviceInfo.getListDeleteTab()==-1){
            mjDeviceInfoService.updateListAddDeviceId(companyId,deviceInfo.getListAddTab(),deviceInfo.getDeviceId());
            map.put("flag",255);
            return RespUtilMach.success(map);
        }

        /**
         * 4、如果list_add_tab=-1 and list_delete_tab>0：
         * 修改mj_device_info表：	list_delete=list_delete_tab
         * 	update mj_device_info set list_delete = list_delete_tab where device_id=[deviceId]
         * 	  返回：flag=255
         */
        if(deviceInfo.getListAddTab()==-1 && deviceInfo.getListDeleteTab()>0){
            mjDeviceInfoService.updateListDelDeviceId(companyId,deviceInfo.getDeviceId(),deviceInfo.getListDeleteTab());
            map.put("flag",255);
            return RespUtilMach.success(map);
        }
        //5、返回：flag=255
        map.put("flag",255);
        return RespUtilMach.success(map);
    }


}
